package com.yqkj.zysoft.upms.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.project.easy.common.db.mybatisplus.core.util.PageConvertTool;
import  com.project.easy.common.util.collection.CollectionUtil;
import  com.project.easy.common.util.dto.PageResDto;
import  com.project.easy.common.util.enums.DelEnums;
import  com.project.easy.common.util.exception.business.BusinessException;
import  com.project.easy.common.util.string.StringUtil;
import com.yqkj.zysoft.upms.entity.FrameworkDepart;
import com.yqkj.zysoft.upms.entity.FrameworkGroup;
import com.yqkj.zysoft.upms.entity.FrameworkRole;
import com.yqkj.zysoft.upms.entity.FrameworkUser;
import com.yqkj.zysoft.upms.entity.FrameworkUserGroup;
import com.yqkj.zysoft.upms.entity.FrameworkUserRole;
import com.yqkj.zysoft.upms.entity.dto.FrameWorkUserAddRequest;
import com.yqkj.zysoft.upms.entity.dto.FrameWorkUserDetailResponse;
import com.yqkj.zysoft.upms.entity.dto.FrameWorkUserUpdateRequest;
import com.yqkj.zysoft.upms.entity.dto.PageUserRequest;
import com.yqkj.zysoft.upms.entity.dto.VerifyCodeAccNoRequest;
import com.yqkj.zysoft.upms.mapper.FrameworkDepartMapper;
import com.yqkj.zysoft.upms.mapper.FrameworkUserMapper;
import com.yqkj.zysoft.upms.service.IFrameworkGroupService;
import com.yqkj.zysoft.upms.service.IFrameworkRoleService;
import com.yqkj.zysoft.upms.service.IFrameworkUserGroupService;
import com.yqkj.zysoft.upms.service.IFrameworkUserRoleService;
import com.yqkj.zysoft.upms.service.IFrameworkUserService;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.DigestUtils;

import java.util.ArrayList;
import java.util.List;
import java.util.Objects;

/**
 * <p>
 *  用户服务实现类
 * </p>
 *
 * @author GreatorMan.cool
 * @since 2022-09-15
 */
@Service
public class FrameworkUserServiceImpl extends ServiceImpl<FrameworkUserMapper, FrameworkUser> implements IFrameworkUserService {


    @Autowired
    private FrameworkUserMapper frameworkUserMapper;

    @Autowired
    private FrameworkDepartMapper frameworkDepartMapper;

    @Autowired
    private IFrameworkUserRoleService frameworkUserRoleService;

    @Autowired
    private IFrameworkUserGroupService frameworkUserGroupService;

    @Autowired
    private IFrameworkRoleService frameworkRoleService;

    @Autowired
    private IFrameworkGroupService frameworkGroupService;

    /**
     * 验证是否存在
     *
     * @param apiToken 令牌
     * @return 返回
     */
    @Override
    public FrameworkUser queryByApiToken(String apiToken) {
        if (StringUtil.isBlank(apiToken)) {
            throw new BusinessException("apiToken不能为空!");
        }
        QueryWrapper<FrameworkUser>  frameworkUserQueryWrapper = new QueryWrapper<>();
        frameworkUserQueryWrapper.eq("api_token", apiToken);
        FrameworkUser frameworkUser = this.frameworkUserMapper.selectOne(frameworkUserQueryWrapper);
        if (Objects.nonNull(frameworkUser.getDepartId()) && StringUtil.isBlank(frameworkUser.getDepartCode())) {
            FrameworkDepart frameworkDepart = this.frameworkDepartMapper.selectById(frameworkUser.getDepartId());
            if (Objects.nonNull(frameworkDepart)) {
                frameworkUser.setDepartCode(frameworkDepart.getInnerCode());
            }
        }
        return frameworkUser;
    }

    /**
     * 用户密码修改
     *
     * @param password 密码
     * @param userId   用户ID
     * @return
     */
    @Override
    public Boolean updatePassword(String password, Long userId) {
        if (StringUtil.isBlank(password)) {
            throw new BusinessException("密码不能为空!");
        }
        if (Objects.isNull(userId)) {
            throw new BusinessException("用户ID不能为空!");
        }
        FrameworkUser frameworkUser = this.frameworkUserMapper.selectById(userId);
        if (Objects.isNull(frameworkUser)) {
            throw  new BusinessException("用户非法!");
        }
        frameworkUser.setPassword(DigestUtils.md5DigestAsHex(password.getBytes()));
        this.frameworkUserMapper.updateById(frameworkUser);
        return Boolean.TRUE;
    }

    /**
     * 用户角色编辑
     *
     * @param roleIds 角色ID集合
     * @param userId  用户ID
     * @return true 成功 false 失败
     */
    @Override
    public Boolean updateRole(String roleIds, Long userId) {
        QueryWrapper<FrameworkUserRole>  userRoleQueryWrapper = new QueryWrapper<>();
        userRoleQueryWrapper.eq("user_id", userId);
        this.frameworkUserRoleService.getBaseMapper().delete(userRoleQueryWrapper);
        if (StringUtil.isNotBlank(roleIds)) {
            List<Long>  roleList = CollectionUtil.parseIds(roleIds);
            if (CollectionUtil.isNotNull(roleList)) {
                List<FrameworkUserRole>   frameworkUserRoles = new ArrayList<>(CollectionUtil.listSize(roleList));
                for (Long roleId :  roleList) {
                    frameworkUserRoles.add(new FrameworkUserRole(userId, roleId));
                }
                this.frameworkUserRoleService.saveBatch(frameworkUserRoles);
            }
        }
        return Boolean.TRUE;
    }

    /**
     * 编辑用户组
     *
     * @param groupId 用户组ID
     * @param userId  用户ID
     * @return true 成功 false 失败
     */
    @Override
    public Boolean updateGroup(Long groupId, Long userId) {
        QueryWrapper<FrameworkUserGroup>  userGroupQueryWrapper = new QueryWrapper<>();
        userGroupQueryWrapper.eq("user_id", userId);
        this.frameworkUserGroupService.getBaseMapper().delete(userGroupQueryWrapper);
        FrameworkUserGroup frameworkUserGroup = new FrameworkUserGroup();
        frameworkUserGroup.setUserId(userId);
        frameworkUserGroup.setGroupId(groupId);
        this.frameworkUserGroupService.save(frameworkUserGroup);
        return Boolean.TRUE;
    }

    /**
     * 编辑部门
     *
     * @param departCode 部门编码
     * @param userId  用户ID
     * @return 返回 true 成功 false 失败
     */
    @Override
    public Boolean updateDepart(String departCode, Long userId) {
        FrameworkUser frameworkUser = this.getFrameworkUser(userId);
        QueryWrapper<FrameworkDepart> frameworkDepartQueryWrapper = new QueryWrapper<>();
        frameworkDepartQueryWrapper.eq("inner_code", departCode);
        frameworkDepartQueryWrapper.eq("has_del", DelEnums.NOT_DEL.getCode());
        FrameworkDepart frameworkDepart = this.frameworkDepartMapper.selectOne(frameworkDepartQueryWrapper);
        if (Objects.isNull(frameworkDepart)) {
            throw  new BusinessException("部门参数非法");
        }
        frameworkUser.setDepartId(frameworkDepart.getId());
        this.frameworkUserMapper.updateById(frameworkUser);
        return Boolean.TRUE;
    }

    /**
     * 用户详情
     *
     * @param id 用户ID
     * @return 返回用户详情
     */
    @Override
    public FrameWorkUserDetailResponse detail(Long id) {
        FrameworkUser frameworkUser = this.getFrameworkUser(id);
        FrameWorkUserDetailResponse response = new FrameWorkUserDetailResponse();
        BeanUtils.copyProperties(frameworkUser, response);
        //用户部门
        if (Objects.nonNull(frameworkUser.getDepartId())) {
            FrameworkDepart frameworkDepart = this.frameworkDepartMapper.selectById(frameworkUser.getDepartId());
            if (Objects.nonNull(frameworkDepart)) {
                response.setDepartCode(frameworkDepart.getInnerCode());
                response.setDepartName(frameworkDepart.getName());
            }
        }
        //角色
        QueryWrapper<FrameworkUserRole>  userRoleQueryWrapper = new QueryWrapper<>();
        userRoleQueryWrapper.eq("user_id", frameworkUser.getId());
        List<FrameworkUserRole> frameworkUserRoles = this.frameworkUserRoleService.getBaseMapper().selectList(userRoleQueryWrapper);
        if (CollectionUtil.isNotNull(frameworkUserRoles)) {
            List<Long> roleList = CollectionUtil.convertToList(frameworkUserRoles, FrameworkUserRole::getRoleId);
            if (CollectionUtil.isNotNull(roleList)) {
                List<FrameworkRole> frameworkRoles = this.frameworkRoleService.getBaseMapper().selectBatchIds(roleList);
                response.setRoleIds(CollectionUtil.convertToString(CollectionUtil.convertToList(frameworkRoles, FrameworkRole::getId)));
                response.setRoleNames(CollectionUtil.convertToStringStr(CollectionUtil.convertToList(frameworkRoles, FrameworkRole::getRoleName)));
            }
        }
        //用户组
        QueryWrapper<FrameworkUserGroup>  userGroupQueryWrapper = new QueryWrapper<>();
        userGroupQueryWrapper.eq("user_id", frameworkUser.getId());
        List<FrameworkUserGroup> frameworkUserGroups = this.frameworkUserGroupService.getBaseMapper().selectList(userGroupQueryWrapper);
        if (CollectionUtil.isNotNull(frameworkUserGroups)) {
            List<FrameworkGroup> frameworkGroups = frameworkGroupService.getBaseMapper().selectBatchIds(CollectionUtil.convertToSet(frameworkUserGroups, FrameworkUserGroup::getGroupId));
            if (CollectionUtil.isNotNull(frameworkGroups)) {
                response.setGroupId(frameworkGroups.get(0).getId());
                response.setGroupName(frameworkGroups.get(0).getGroupName());
            }
        }

        return response;
    }

    /**
     * 新增
     *
     * @param frameWorkUserAddRequest 参数
     * @return 返回 true 成功 false 失败
     */
    @Override
    @Transactional(rollbackFor =  Exception.class)
    public Long add(FrameWorkUserAddRequest frameWorkUserAddRequest) {
        //验证登陆账户唯一性
        QueryWrapper<FrameworkUser> frameworkUserQueryWrapper = new QueryWrapper<>();
        frameworkUserQueryWrapper.eq("acc_no", frameWorkUserAddRequest.getAccNo());
        frameworkUserQueryWrapper.eq("has_del", DelEnums.NOT_DEL.getCode());
        List<FrameworkUser> frameworkUsers = this.frameworkUserMapper.selectList(frameworkUserQueryWrapper);
        if (!CollectionUtil.isNull(frameworkUsers)) {
            throw  new BusinessException("登陆账户不能重复");
        }
        FrameworkUser frameworkUser = new FrameworkUser();
        BeanUtils.copyProperties(frameWorkUserAddRequest, frameworkUser);
        if (StringUtil.isNotBlank(frameWorkUserAddRequest.getDepartId())) {
            QueryWrapper<FrameworkDepart> frameworkDepartQueryWrapper = new QueryWrapper<>();
            frameworkDepartQueryWrapper.eq("inner_code", frameWorkUserAddRequest.getDepartId());
            frameworkDepartQueryWrapper.eq("has_del", DelEnums.NOT_DEL.getCode());
            FrameworkDepart frameworkDepart = this.frameworkDepartMapper.selectOne(frameworkDepartQueryWrapper);
            if (Objects.isNull(frameworkDepart)) {
                throw  new BusinessException("部门参数非法");
            }
            frameworkUser.setDepartCode(frameworkDepart.getInnerCode());
            frameworkUser.setDepartId(frameworkDepart.getId());
        }
        frameworkUser.setPassword(DigestUtils.md5DigestAsHex(frameworkUser.getPassword().getBytes()));
        boolean save = this.save(frameworkUser);
        if (save) {
            //写入角色
            if (StringUtil.isNotBlank(frameWorkUserAddRequest.getRoleIds())) {
                List<Long>  roleIds = CollectionUtil.parseIds(frameWorkUserAddRequest.getRoleIds());
                if (CollectionUtil.isNotNull(roleIds)) {
                    List<FrameworkUserRole>   frameworkUserRoles = new ArrayList<>(CollectionUtil.listSize(roleIds));
                    for (Long roleId :  roleIds) {
                        frameworkUserRoles.add(new FrameworkUserRole(frameworkUser.getId(), roleId));
                    }
                    this.frameworkUserRoleService.saveBatch(frameworkUserRoles);
                }
            }
            if (Objects.nonNull(frameWorkUserAddRequest.getGroupId())) {
                FrameworkUserGroup frameworkUserGroup = new FrameworkUserGroup();
                frameworkUserGroup.setGroupId(frameWorkUserAddRequest.getGroupId());
                frameworkUserGroup.setUserId(frameworkUser.getId());
                this.frameworkUserGroupService.save(frameworkUserGroup);
            }
            return frameworkUser.getId();
        }
        throw  new BusinessException("存储失败");
    }
    /**
     * 更新数据
     *
     * @param frameWorkUserUpdateRequest 参数
     * @return true 成功 false 失败
     */
    @Override
    public Boolean updateObject(FrameWorkUserUpdateRequest frameWorkUserUpdateRequest) {
        FrameworkUser frameworkUser = this.getFrameworkUser(frameWorkUserUpdateRequest.getId());
        frameworkUser.setNickName(frameWorkUserUpdateRequest.getNickName());
        frameworkUser.setUsername(frameWorkUserUpdateRequest.getUsername());
        frameworkUser.setEmail(frameWorkUserUpdateRequest.getEmail());
        frameworkUser.setMobile(frameWorkUserUpdateRequest.getMobile());
        frameworkUser.setSex(frameWorkUserUpdateRequest.getSex());
        frameworkUser.setJob(frameWorkUserUpdateRequest.getJob());
        frameworkUser.setBirthDay(frameWorkUserUpdateRequest.getBirthDay());
        return  this.updateById(frameworkUser);
    }
    /**
     * 获取用户数据
     * @param id ID
     * @return 返回
     */
    private FrameworkUser getFrameworkUser(Long id) {
        if (Objects.isNull(id)) {
            throw  new BusinessException("ID不能为空");
        }
        FrameworkUser frameworkUser = this.frameworkUserMapper.selectById(id);
        if (Objects.isNull(frameworkUser)) {
            throw  new BusinessException("ID非法");
        }
        return frameworkUser;
    }
    /**
     * 分页
     *
     * @param pageUserRequest 分页查询条件
     * @return 返回数据
     */
    @Override
    public PageResDto<FrameworkUser> pageList(PageUserRequest pageUserRequest) {
        Page<FrameworkUser> page = new Page<>(pageUserRequest.getPageNum(), pageUserRequest.getPageSize());
        QueryWrapper<FrameworkUser> queryWrapper = new QueryWrapper<>();
        if (StringUtil.isNotBlank(pageUserRequest.getAccNo())) {
            queryWrapper.like("acc_no", pageUserRequest.getAccNo());
        }
        if (StringUtil.isNotBlank(pageUserRequest.getName())) {
            queryWrapper.eq("username", pageUserRequest.getName());
        }
        if (Objects.nonNull(pageUserRequest.getDepartId())) {
            queryWrapper.eq("depart_id", pageUserRequest.getDepartId());
        }
        if (Objects.nonNull(pageUserRequest.getGroupId())) {
            queryWrapper.eq("group_id", pageUserRequest.getGroupId());
        }
        queryWrapper.ne("id", pageUserRequest.getApiContextParamUserInfo().getUserId());
        queryWrapper.likeRight("depart_code", pageUserRequest.getApiContextParamUserInfo().getDepartCode());
        queryWrapper.eq("has_del", Boolean.FALSE);
        Page<FrameworkUser> result  = this.baseMapper.selectPage(page, queryWrapper);
        return PageConvertTool.convert(result);
    }

    /**
     * 验证数据
     *
     * @param verifyCodeAccNoRequest 参数
     * @return true 验证成功 false 验证失败
     */
    @Override
    public Boolean verifyCode(VerifyCodeAccNoRequest verifyCodeAccNoRequest) {
        return null;
    }

    /**
     * 启用
     *
     * @param id ID
     * @return true 启用成功 false 启用失败
     */
    @Override
    public Boolean able(Long id) {
        FrameworkUser frameworkUser = this.getFrameworkUser(id);
        if (frameworkUser.getStatus()) {
            throw  new BusinessException("启用不能再次启用!");
        }
        frameworkUser.setStatus(Boolean.TRUE);
        this.baseMapper.updateById(frameworkUser);
        return Boolean.TRUE;
    }

    /**
     * 禁用
     *
     * @param id ID
     * @return true 启用成功 false 启用失败
     */
    @Override
    public Boolean disAble(Long id) {
        FrameworkUser frameworkUser = this.getFrameworkUser(id);
        if (!frameworkUser.getStatus()) {
            throw  new BusinessException("禁用不能再次禁用!");
        }
        frameworkUser.setStatus(Boolean.FALSE);
        this.baseMapper.updateById(frameworkUser);
        return Boolean.TRUE;
    }
}
